<template>
  <el-container>
    <el-header class="header">{{launcher_name}}</el-header>
    <el-main style="margin-left: 20px">
      <div style="margin-bottom: 20px;">
        <el-button type="primary" @click="addTab(editableTabsValue)">新增页面</el-button>
        <el-button  type="primary" @click="sortPageVisible=true">调整页面顺序</el-button>
      </div>
      <el-tabs v-model="editableTabsValue" type="card" closable @tab-remove="removeTab" @tab-click="tabClick">
        <el-tab-pane
          v-for="(item, index) in pages"
          :key="`${index+''}`"
          :label="`第${index+1}页`"
          :name="`${index+''}`"
        >
        </el-tab-pane>
      </el-tabs>

      <el-form ref="form" :model="form" label-width="80px" style="width: 500px">
        <el-form-item label="标题">
          <el-input placeholder="请输入标题" v-model="form.title" @change="changeCurrentForm"></el-input>
        </el-form-item>
        <el-form-item label="定制图">
          <el-upload
            class="avatar-uploader"
            action
            :show-file-list="false"
            :on-change="pageBackImgUpload">
            <img v-if="form.customBg" :src="form.customBg" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <div slot="tip" class="el-upload__tip" style="margin-top: -7px">只能上传jpg/png文件，且不超过3M</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div class="divBody">
        <div class="imgContainer">
          <canvas id="pageCanvas" class="canvasClass" @mousedown='mousedown' @mousemove='mousemove'
                  @mouseup='mouseup'></canvas>
          <img id="image" class="imageClass" :src="form.customBg"/>
        </div>
      </div>
      <el-dialog :title="editSubjects ? '修改配置' : '新增配置'" :visible.sync="dialogVisible" width="30%" @close="ruleFormClosed">
        <el-form :model="ruleForm" ref="ruleForm" label-width="100px" :rules="rules" class="demo-ruleForm">
          <el-form-item label="配置类型:" prop="type">
            <el-select v-model="ruleForm.type" placeholder="请选择" @change="setVisibleStats">
              <el-option
                v-for="item in configOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="配置名称:" prop="name" style="width: 300px" v-show="!isVisibleApp">
            <el-input placeholder="请输入配置名称" v-model="ruleForm.name" :disabled="isVisibleApp"></el-input>
          </el-form-item>
          <el-form-item label="App选择:" prop="appId" v-show="ruleForm.type==1">
            <el-select v-model="ruleForm.app_id" placeholder="请选择" @change="(event,name) => {changeAppSelect(event,'charge')}" filterable>
              <el-option
                v-for="item in appOptions"
                :key="item.app_id"
                :label="item.column_name"
                :value="item.app_id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="App选择:" prop="appId" v-show="ruleForm.type==4">
            <el-select v-model="ruleForm.app_id" placeholder="请选择" @change="(event,name) => {changeAppSelect(event,'self')}">
              <el-option
                v-for="item in selfAppOptions"
                :key="item.app_id"
                :label="item.column_name"
                :value="item.app_id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="跳转方式:" prop="linkType" v-show="ruleForm.type==5">
            <el-radio-group v-model="ruleForm.linkType">
              <el-radio :label="1">Launcher应用内跳转</el-radio>
              <el-radio :label="2">浏览器跳转</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="跳转网址:" prop="linkUrl" v-show="ruleForm.type==5">
            <el-input placeholder="请输入跳转链接" v-model="ruleForm.linkUrl"></el-input>
          </el-form-item>
          <el-form-item label="视频内容选择:" prop="contentUrl" v-show="ruleForm.type==3">
            <el-select v-model="ruleForm.contentUrl" placeholder="请选择" >
              <el-option
                v-for="item in videoOptions"
                :key="item.content_id"
                :label="item.content_name"
                :value="item.content_url">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="音频内容选择:" prop="contentUrl" v-show="ruleForm.type==2">
            <el-select v-model="ruleForm.contentUrl" placeholder="请选择">
              <el-option
                v-for="item in voiceOptions"
                :key="item.content_id"
                :label="item.content_name"
                :value="item.content_url">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="文档内容选择:" prop="contentUrl" v-show="ruleForm.type==7">
            <el-select v-model="ruleForm.contentUrl" placeholder="请选择">
              <el-option
                v-for="item in fileOptions"
                :key="item.content_id"
                :label="item.content_name"
                :value="item.content_url">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="图片内容选择:" prop="contentUrl" v-show="ruleForm.type==6">
            <el-select v-model="ruleForm.contentUrl" placeholder="请选择">
              <el-option
                v-for="item in imgOptions"
                :key="item.content_id"
                :label="item.content_name"
                :value="item.content_url">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button @click="cancelForm">取消</el-button>
            <el-button v-if="editSubjects" type="primary" @click="edittoForm('ruleForm')">确定</el-button>
            <el-button v-else type="primary" @click="addtoForm('ruleForm')">确定</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>

      <div>
        <el-row>
          <el-col :span="10">
            <h4>配置列表</h4>
          </el-col>
          <el-col :span="14">
            <el-button type="primary" @click="backToLauncher()">返回</el-button>
            <el-button type="primary" @click="onsubmit()">保存</el-button>
          </el-col>
        </el-row>
      </div>

      <el-table :data="form.iconLinkList" stripe style="width: 50%">
        <el-table-column label="编号">
          <template slot-scope="scope">
            <span>{{scope.$index+1}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="名称"></el-table-column>
        <el-table-column prop="type" label="配置类型">
          <template slot-scope="scope">
            <span v-if="scope.row.type==1">内容推荐App</span>
            <span v-if="scope.row.type==2">音频类型</span>
            <span v-if="scope.row.type==3">视频类型</span>
            <span v-if="scope.row.type==4">账户私有App</span>
            <span v-if="scope.row.type==5">网页跳转</span>
            <span v-if="scope.row.type==6">图形类型</span>
            <span v-if="scope.row.type==7">文档类型</span>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>

      </el-table>
      <el-dialog title="页面排序" :visible.sync="sortPageVisible" width="70%" :before-close="closeSort">
        <div class="app-container">
          <ul class="projset-content">
            <draggable
              :forceFallback="true"
              :list="pages"
              handle=".dargBtn"
              :animation="1000"
              filter=".undraggable"
              fallbackClass="fallbackStyle"
              ghostClass="item_ghost"
              chosenClass="chosenStyle"
              dragClass="dragStyle"
            >
              <li v-for="(item, index) in pages" :key="index" class="draggable">
                <div class="dargBtn">
                  <svg-icon icon-class="drag" />
                </div>
                <img :src="item.customBg" alt="">
                <span>{{item.title}}</span>
              </li>
            </draggable>
          </ul>
        </div>
      </el-dialog>

    </el-main>
  </el-container>
</template>

<script>
  import {addLauncherContent, getContentOption, queryLauncherContent} from "@/api/launcherMade";
  import {ossImage} from "@/utils/ossUpload";
  import draggable from 'vuedraggable'

  export default {
    components: { draggable},
    data() {
      return {
        editableTabsValue: '0',
        tabIndex: 0,
        form: {
          title: '',
          customBg: '',
          iconLinkList: [],
          launcher_id: this.$route.query.launcher_id,
        },
        ruleForm: {
          name: '',
          type: 1,
          packageName: '',
          surfaceName: '',
          packageUrl: '',
          scheme: '',
          action: '',
          app_id: '',
          linkType: 1,
          linkUrl: '',  //网页跳转链接
          contentUrl: '',  //内容链接
        },
        dialogVisible: false,
        editSubjects: false,
        editIndex: -1,
        rules: {
          name: [
            {required: true, message: '请输入配置名称', trigger: 'blur'},
          ],
          type: [
            {required: true, message: '请选择配置类型', trigger: 'change'}
          ],
        },
        //canvas所需数据
        start_x: '',
        start_y: '',
        end_x: '',
        end_y: '',
        flag: false,
        //总的数据
        pages: [{
          title: '',
          customBg: '',
          iconLinkList: []
          }
        ],
        launcher_id: this.$route.query.launcher_id,
        launcher_name: this.$route.query.launcher_name,
        configOptions: [
          {label: '内容推荐App', value: 1},
          {label: '音频类型', value: 2},
          {label: '视频类型', value: 3},
          {label: '账户私有App', value: 4},
          {label: '网页跳转', value: 5},
          {label: '图形类型', value: 6},
          {label: '文档类型', value: 7}
          ],
        appOptions: [],
        selfAppOptions: [],
        voiceOptions: [],  //音频类型文件
        videoOptions: [],  //视频类型文件
        imgOptions: [],    //图形类型文件
        fileOptions: [],   //文档类型文件
        sortPageVisible: false,
        width: '',
        height: '',
        isVisibleApp: true
      }
    },
    created() {
      this.queryLauncherInfo()
      this.getContentOption()
    },
    methods: {
      addTab(targetName) {
        var num = this.pages.length
        if(num >= 12) {
          this.$message.error("最多添加十二个页面~")
          return
        }
        this.editableTabsValue = this.tabIndex + '';
        if (num > 0) {
          this.editableTabsValue = num + '';
        }
        this.pages.push({
          title: '',
          customBg: '',
          iconLinkList: [],
          launcher_id: this.launcher_id
        })
        this.form = {
          title: '',
          customBg: '',
          iconLinkList: [],
          launcher_id: this.launcher_id
        }
        this.tabIndex += 1
        //清空画布
        const canvas = document.getElementById('pageCanvas')
        this.ctx.clearRect(0, 0, canvas.width, canvas.height);
      },
      removeTab(targetName) {
        if(this.pages.length == 1) {
          this.$message({type: 'error', message: '请至少保留一个页面'})
          return
        }
        this.$confirm('确定删除该定制页面?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let tabs = this.pages
          let activeName = this.editableTabsValue;
          if (activeName === targetName) {
            tabs.forEach((tab, index) => {
              if (tab.index == targetName) {
                let nextTab = tabs[index + 1] || tabs[index - 1];
                if (nextTab) {
                  activeName = nextTab.name;
                }
              }
            });
          }
          this.editableTabsValue = (activeName-1).toString();
          tabs.splice(targetName, 1)
          this.pages = tabs
          if(this.pages[activeName-1] != undefined) {
            this.form = this.pages[activeName-1]
          }
          this.resetAndDraw()
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      getContentOption() {
        getContentOption({'userId': localStorage.getItem('ID')}).then(res => {
          this.videoOptions = res.data[1]
          this.voiceOptions = res.data[2]
          this.fileOptions = res.data[3]
          this.imgOptions = res.data[4]
        })
      },
      tabClick() {
        let currentPage = parseInt(this.editableTabsValue)
        let currentForm = this.pages[currentPage]
        if (currentForm) {
          this.form = currentForm
        }
        this.resetAndDraw()
      },
      changeAppSelect(event, name){
        let tempAppOptions = name == 'charge' ? this.appOptions : this.selfAppOptions
        tempAppOptions.filter(item => {
          if (item.app_id == event){
            this.ruleForm.packageName = item.app_package
            this.ruleForm.packageUrl = item.app_url
            this.ruleForm.scheme = item.scheme
            this.ruleForm.action = item.action
            this.ruleForm.name = item.column_name
          }
        })
      },

      handleEdit(index, row) {
        this.editIndex = index
        this.ruleForm = row
        this.editSubjects = true
        this.dialogVisible = true
      },
      handleDelete(index, row) {
        var delData = this.form.iconLinkList[index]
        if (delData) {
          this.form.iconLinkList.splice(index, 1)
          //矩形框同步删除
          this.delRect(delData.start_x, delData.start_y, delData.width, delData.height)
        }
        //删除后自动保存
        // this.onsubmit()
      },
      resetFields() {
        this.ruleForm.name = ''
        this.ruleForm.packageName = ''
        this.ruleForm.surfaceName = ''
        this.ruleForm.packageUrl = ''
        this.ruleForm.scheme = ''
        this.ruleForm.action = ''
        this.ruleForm.app_id = ''
        this.ruleForm.linkUrl = ''
        this.ruleForm.contentUrl = ''
      },
      cancelForm() {
        this.dialogVisible = false
        this.resetAndDraw()
      },
      addtoForm() {
        // 提交保存坐标
        this.form.iconLinkList.push({
          start_x: this.start_x,
          start_y: this.start_y,
          width: this.end_x - this.start_x,
          height: this.end_y - this.start_y,
          name: this.ruleForm.name,
          type: this.ruleForm.type,
          packageName: this.ruleForm.packageName,
          surfaceName: this.ruleForm.surfaceName,
          packageUrl: this.ruleForm.packageUrl,
          scheme: this.ruleForm.scheme,
          action: this.ruleForm.action,
          app_id: this.ruleForm.app_id,
          linkType: this.ruleForm.linkType,
          linkUrl: this.ruleForm.linkUrl,  //网页跳转链接
          contentUrl: this.ruleForm.contentUrl
        })
        this.changeCurrentForm()
        this.dialogVisible = false
      },
      edittoForm() {
        this.form.iconLinkList[this.editIndex] = this.ruleForm
        this.changeCurrentForm()
        this.dialogVisible = false
      },
      mousedown(event) {
        // 鼠标开始记录坐标
        this.flag = true
        this.start_x = event.offsetX
        this.start_y = event.offsetY
      },
      mousemove(event) {
        // 鼠标移动过程中画矩形框
        this.drawRect(event);
      },
      drawRect(event) {
        if (this.flag) {
          this.end_x = event.offsetX
          this.end_y = event.offsetY
          // 清除画布，相当于橡皮擦？
          const canvas = document.getElementById('pageCanvas')
          this.ctx.clearRect(0, 0, canvas.width, canvas.height);
          this.ctx.fillStyle = 'red'
          this.ctx.font = '18px sans-serif'
          // 绘制保存的坐标
          this.form.iconLinkList.forEach((value, index) => {
            this.ctx.strokeRect(value.start_x, value.start_y, value.width, value.height);
            var halfx = value.start_x + value.width / 2
            var halfy = value.start_y + value.height / 2
            this.ctx.fillText(index + 1, halfx, halfy, value.width);
          })

          // 开始绘制
          this.ctx.beginPath();
          //设置线条颜色，必须放在绘制之前
          this.ctx.strokeStyle = 'red';
          // 线宽设置，必须放在绘制之前
          this.ctx.lineWidth = 1;
          // 进行矩形绘制(矩形左上角的 x 坐标,矩形左上角的 y 坐标，矩形的宽度，矩形的高度)
          this.ctx.strokeRect(this.start_x, this.start_y, this.end_x - this.start_x, this.end_y - this.start_y);
          var num = this.form.iconLinkList.length + 1
          var halfx = parseInt(this.start_x + (this.end_x - this.start_x) / 2)
          var halfy = parseInt(this.start_y + (this.end_y - this.start_y) / 2)
          this.ctx.fillText(num, halfx, halfy, this.width);
        }
      },

      delRect(x, y, width, height) {
        this.ctx.clearRect(x - 2, y - 2, width + 3, height + 3);
      },

      mouseup() {
        this.resetFields()
        this.flag = false
        this.dialogVisible = true
      },

      //清空画布并且画出当前页面的框选
      resetAndDraw() {
        //先清空画布
        const canvas = document.getElementById('pageCanvas')
        this.ctx.clearRect(0, 0, canvas.width, canvas.height);
        // 绘制保存的坐标
        this.ctx.fillStyle = 'red'
        this.ctx.strokeStyle = 'red';
        this.ctx.font = '18px sans-serif'
        this.form.iconLinkList.forEach((value, index) => {
          this.ctx.strokeRect(value.start_x, value.start_y, value.width, value.height);
          var halfx = value.start_x + value.width / 2
          var halfy = value.start_y + value.height / 2
          this.ctx.fillText(index + 1, halfx, halfy, value.width);
        })
      },
      changeCurrentForm() {
        let currentPage = parseInt(this.editableTabsValue)
        this.pages[currentPage] = this.form
      },

      onsubmit() {
        let addForm = {
          last_ip: sessionStorage.getItem("Ip"),
          userId: localStorage.getItem("ID"),
          launcher_id: this.launcher_id,
          pagesData: JSON.parse(JSON.stringify(this.pages)),
          type: 2    //type 1：样式定制 2：页面定制
        }
        addLauncherContent(addForm).then(res => {
          this.$message.success(res.msg)
          this.queryLauncherInfo()
          this.dialogFormVisible = false
        }).catch(err => {
        })
      },

      //获取页面定制数据
      queryLauncherInfo() {
        var listQuery = {
          launcher_id: this.launcher_id,
          last_ip: sessionStorage.getItem("Ip"),
          userId: localStorage.getItem("ID"),
          type: 2    //type 1：样式定制 2：页面定制
        }
        queryLauncherContent(listQuery).then(res => {
          if (res.code == 200) {
            if(res.data.page_content){
              this.pages = res.data.page_content
              this.form = this.pages[this.editableTabsValue]
              this.resetAndDraw()
            }
            this.width = res.data.width
            this.height = res.data.height
            this.appOptions = res.data.appOptions
            this.selfAppOptions = res.data.selfAppOptions
          } else {
            this.$message.error(res.msg)
          }
        }).catch(err => {
        })
      },
      pageBackImgUpload(res, file) {
        file = res.raw
        const isJPG = file.type === 'image/jpeg'
        const isPNG = file.type === 'image/png'
        const isLt3M = file.size / 1024 / 1024 < 3
        if (!isJPG && !isPNG) {
          this.$message.error('上传图片只能是jpg或png格式!')
          return false
        }
        if (!isLt3M) {
          this.$message.error('上传图片大小不能超过 3MB!')
          return false
        }
        if(this.width && this.height) {
          this.valWidthAndHeight(file, this.width, this.height, res.name)
        }
      },

      valWidthAndHeight:function(file, validWidth, validHeight, name){
        return new Promise(function(resolve, reject) {
          let width = validWidth  //图片宽度
          let height = validHeight ; //图片高度
          let _URL = window.URL || window.webkitURL;
          let image = new Image();
          image.src = _URL.createObjectURL(file);
          image.onload = function() {
            let valid = image.width == width && image.height == height;
            valid ? resolve() : reject();
          };
        }).then(()=>{
          ossImage(file, name).then(res => {//图片上传
            this.form.customBg = res
            this.changeCurrentForm()
          }).catch(err => {
            console.log('error:', err)
          })
        }).catch(error=>{
          this.$message.error("上传图片尺寸不符合,只能是"+validWidth+"*"+validHeight+"!");
        })

      },
      closeSort(){
        this.sortPageVisible = false
        this.form = this.pages[this.editableTabsValue]
        this.resetAndDraw()
      },
      setVisibleStats(type){
        this.ruleForm.scheme=''
        this.ruleForm.action=''
        this.ruleForm.packageName=''
        this.ruleForm.app_id=''
        this.ruleForm.surfaceName=''
        this.ruleForm.name=''
        this.ruleForm.linkUrl = ''
        this.ruleForm.contentUrl = '';
        switch (type) {
          case 1:
          case 4:
            this.isVisibleApp = true;
            break
          case 2:
          case 3:
          case 5:
          case 6:
          case 7:
            this.isVisibleApp = false;
            break
        }
      },
      backToLauncher() {
        this.$confirm('系统可能不会自动保存您的修改', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$router.push({name:'launcherUI'});
        })
      },
      ruleFormClosed() {
        this.editSubjects=false
        this.$nextTick(() => {
          this.ruleForm = this.$options.data.call(this).ruleForm
        })
      },

    },
    mounted() {
      this.$nextTick(() => {
        const canvas = document.getElementById('pageCanvas')
        this.ctx = canvas.getContext("2d");
        const bg = document.getElementsByClassName('imgContainer')[0] //动态获取父元素 宽高--->赋值
        canvas.width = bg.clientWidth
        canvas.height = bg.clientHeight
      });
    },
  }
</script>

<style scoped>
  .divBody {
    overflow: auto;
  }

  .imgContainer {
    position: relative;
    width: 640px;
    height: 400px;
  }

  .canvasClass {
    width: 640px;
    height: 400px;
    max-width: 100%;
    max-height: 100%;
    border: 1px solid red;
    position: absolute;
  }

  canvas {
    display: inline-block;
    overflow-clip-margin: content-box;
    /*overflow: clip;*/
  }

  .imageClass {
    width: auto;
    height: auto;
    max-width: 100%;
    max-height: 100%;
    overflow-clip-margin: content-box;
  }

</style>

<style >
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 63px;
    line-height: 63px;
    text-align: center;
  }

  .avatar {
    width: 100px;
    height: 63px;
    display: block;
  }
</style>


<style scoped lang="scss">
  .header{
    height: 60px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .app-container{
    background: #ffffff;
    height: 100%;
    .dargBtn-lock{
      margin: 0px 50px;
      color: #2ea9df;
    }
    .dragStyle {
      padding: 10px;
      border-radius: 4px;
      opacity: 1;
    }
    .fallbackStyle{
      padding: 10px;
      border-radius: 4px;
      opacity: 1;

    }
    .chosenStyle {
      padding: 10px;
      border-radius: 4px;
      opacity: 1 !important;

    }
    .item_ghost {
      opacity: 0 !important;
    }
    .projset-content{
      list-style-type: none;
      position: relative;
      li{
        display: inline-block;
        margin: 10px;
      }
      img{
        width: 141px;
        height: 100px;
      }
      span{
        justify-content: center;
        display: flex;
      }
      .dargBtn{
        position: absolute;
        line-height: 100px;
        text-align: center;
        width: 141px;
        height: 100px;
        display: none;
        color: white;
        // background: rgba(101, 101, 101, 0.6);
      }
      .draggable{
        cursor: pointer;
        width: 141px;
        height: 100px;
      }
      .draggable:hover .dargBtn{
        display: block;
      }

    }
  }
</style>

